<?php

namespace App\Http\Controllers\UserApi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Services\Api\UserServices;
use phpDocumentor\Reflection\Types\Self_;

class UserController extends BaseController
{
    public function __construct(User $user, UserServices $services)
    {
        $this->user = $user;
        $this->services = $services;
    }

    public function user_info(Request $request)
    {
        $data = $this->services->user_info(auth('api')->user()->id, $this->user);
        return $this->success($data);
    }

    public function update_head_nickname(Request $request)
    {
        try {

            User::$modify = false;

            $user_info = $this->services->user_info(auth('api')->user()->id, $this->user);

            $image_head = !empty($request->file('head')) ? $request->file('head') : [];

            $update = [];

            if (!empty($image_head)) {                
                if (file_exists("./" . $user_info->head_img) && $user_info->head_img != "/upload/head/img.jpg") {
                    @unlink("./" . $user_info->head_img);
                }

                $path = $image_head->store('/images/' . date('Ymd'));

                $update['head_img'] = "/upload/" . $path;

            }

            if (!empty($request->nickname)) {

                $update['nickname'] = $request->nickname ?? '';

            }


            if (!empty($update)) {

                (new User())->where('id', auth('api')->user()->id)->update($update);

            }

        } catch (\Exception $e) {

            return self::fail($e->getMessage());

        }

        return self::success([]);
    }

    public function body_weight()
    {
        $edit_type = \request()->edit_type ?? '';
        $result = [];

        try {
            switch ($edit_type) {
                case 'add':
                    $this->services->body_weight_add();
                    break;
                case 'lists':
                    $result = $this->services->body_weight_lists();
                    break;
                default:
                    throw new \Exception('请传edit_type参数');
                    break;
            }

        } catch (\Exception $e) {

            return self::fail($e->getMessage());

        }

        return self::success($result);
    }
}
